package com.example.springcloudmodelserver.controller;

import com.example.springcloudmodelserver.Result.JsonResult;
import com.example.springcloudmodelserver.Result.StatusCode;
import com.example.springcloudmodelserver.entity.Model;
import com.example.springcloudmodelserver.entity.User;
import com.example.springcloudmodelserver.service.Modelservice;
import com.example.springcloudmodelserver.service.Uploadservice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;
import java.util.UUID;
import com.alibaba.fastjson.JSON;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

@Slf4j
@RestController
@RequestMapping("/model")
@ResponseBody
public class ModelController {
    @Autowired
    private Modelservice modelservice;

    @Autowired
    private Uploadservice uploadservice;

    private static String modelId;

    /**功能说明书保存路径*/
    String funpath = "D:\\upload\\fun\\";

    @GetMapping("/test")
    public String testModel(){
        return "Test Model Server";
    }

    @PostMapping("/funUpload")
    public JsonResult funUpload (@RequestParam("file") MultipartFile file,
                                 @RequestParam("modelid") @Valid String modelid) throws IOException {
        if(Objects.isNull(file) || file.isEmpty()){
            return new JsonResult(StatusCode.FILE_ERROR.getCode(),"文件为空，请重新上传");
        }
        File uploadfile = new File(funpath+file.getOriginalFilename());
        try {
            file.transferTo(uploadfile);
        } catch (IOException e) {
            return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(),e);
        }
        String path = uploadfile.getPath();
        modelservice.updatefunpath(modelid,path);
        return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage());
    }

    @PostMapping("/modelUpload")
    public JsonResult modelUpload(@RequestParam("file") MultipartFile file,
                              @RequestParam("modelid") @Valid String modelid) throws IOException {
        if (Objects.isNull(file) || file.isEmpty()) {

            return new JsonResult(StatusCode.FILE_ERROR.getCode(), "文件为空，请重新上传");
        }
//        if(!uploadservice.checkType(file)){
//            return new JsonResult(StatusCode.FILE_ERROR.getCode(), "文件格式错误，请重新上传");
//        }
//        if(modelservice.queryModelByModelid(modelid) == null){
//            return new JsonResult(StatusCode.INFO_ERROR.getCode(), "模型不存在");
//        }
        String filemd5 = uploadservice.checkMD5(file);
        if(modelservice.queryModelByFileMD5(filemd5) != null){
            return new JsonResult(StatusCode.FILE_ERROR.getCode(), "文件已存在，请勿重复上传");
        }
        //将上传文件保存到路径
        File uploadFile = uploadservice.UploadFile(file);
        try {
            file.transferTo(uploadFile);
        } catch (IOException e) {
            return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(),e);
        }
        String path = uploadFile.getPath();
        /**更新模型文件上传路径*/
        modelservice.updateModelFilepath(modelid,path);
        /**更新模型的MD5*/
        modelservice.updateModelFileMD5(modelid,filemd5);
        modelId = modelid;
        return new JsonResult(StatusCode.SUCCESS.getCode(),StatusCode.SUCCESS.getMessage());
    }

    @GetMapping("/getModelId")
    public String getModelId() {
        return modelId;
    }

    @PostMapping("/modelIdentityUpdate")
    public JsonResult modelIdentityUpdate(@RequestParam("username")  String username,
                                          @RequestParam("truename") @Valid String truename,
                                          @RequestParam("identifying") @Valid String identityinfo,
                                          @RequestParam("identities") MultipartFile identityfile) throws IOException {
        if(modelservice.queryUserByTruename(truename)!=null){
            return new JsonResult(StatusCode.INFO_ERROR.getCode(), "资质信息已登记");
        }
        if (modelservice.queryUser(username) == null){
            return new JsonResult(StatusCode.INFO_ERROR.getCode(),"该用户尚未注册");
        }
        if (Objects.isNull(identityfile) || identityfile.isEmpty()) {
            return new JsonResult(StatusCode.FILE_ERROR.getCode(), "文件为空，请重新上传");
        }
        if(!uploadservice.checkIndentityType(identityfile)){
            return new JsonResult(StatusCode.FILE_ERROR.getCode(), "文件格式错误，请重新上传");
        }
        String originalFilename = identityfile.getOriginalFilename();
        String dFilename = UUID.randomUUID() + originalFilename;
        String path = "D:\\upload" + username + "\\";
        File uploadIdentityfile = new File(path+dFilename);
        try {
            identityfile.transferTo(uploadIdentityfile);
        }catch (IOException e) {
            return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(),e);
        }
//        String identitypath = uploadIdentityFile.getPath();
        modelservice.updateModelIdentity(username,truename,identityinfo,path+dFilename);
        return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage());
    }


    @PostMapping("/modelInfoUpload")
    public JsonResult modelInfoUpload(@RequestBody @Valid Model model) {
        Model existmodel = modelservice.queryModelByModelname(model.getModelname());
        if(existmodel != null) {
            return new JsonResult(StatusCode.INFO_ERROR.getCode(), "模型名称已经存在");
        }
        if(modelservice.queryModel(model.getUsername())==null){
            return new JsonResult((StatusCode.INFO_ERROR.getCode()),"用户名不存在");
        }
        modelservice.updateModel(model);
        return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage());
    }

    @GetMapping("/getModelFunction")
    public JsonResult fundownload( HttpServletResponse response)throws IOException {
        String filename = "function.doc";
        File file = new File("D:\\upload\\function.doc");
        if(file.exists()) {
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition","attachment;filename=" + filename);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis =null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer,0,i);
                    i = bis.read(buffer);
                }
                return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage());
            }catch (IOException e){
                return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(),e);
            }finally {
                if(bis !=null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(),e);
                    }
                }
                if(fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(),e);
                    }
                }
            }

        }
        return new JsonResult(StatusCode.FILE_ERROR.getCode(), "功能说明文件下载错误");
    }


    @GetMapping("/getModelTsetreport")
    public JsonResult reportdownload( HttpServletResponse response)throws IOException {
        String filename = "test-report.docx";
        File file = new File("D:\\upload\\test-report.docx");
        if(file.exists()) {
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition","attachment;filename=" + filename);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis =null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer,0,i);
                    i = bis.read(buffer);
                }
                return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage());
            }catch (IOException e){
                return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(),e);
            }finally {
                if(bis !=null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(),e);
                    }
                }
                if(fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        return new JsonResult(StatusCode.EXCEPTION.getCode(), StatusCode.EXCEPTION.getMessage(),e);
                    }
                }
            }

        }
        return new JsonResult(StatusCode.FILE_ERROR.getCode(), "测试报告文件下载错误");
    }




    @GetMapping("/getModelByModelname")
    public Model getModelByModelname(@RequestParam("modelname") String modelname) {
        return modelservice.queryModelByModelname(modelname);
    }

    @GetMapping("/getModelByModelId")
    public Model getModelByModelId(@RequestParam("id") String id) {
        return modelservice.queryModelByModelid(id);
    }

    @GetMapping("/deleteModelByModelname")
    public JsonResult deleteModelByModelname(@RequestParam("modelname") String modelname) {
        modelservice.deleteModel(modelname);
        return new JsonResult(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage());
    }



}
